<!--每日一练是练习模式，可以查看答案-->

<script setup>
import PaperApis from '@/apis/paper.js'
import CommonQuestion from "@/components/common/CommonQuestion.vue";
import {computed} from "vue";
import {ElMessage} from "element-plus";
import QuestionApis from "@/apis/question.js";
import NoteApis from "@/apis/note.js";


const route = useRoute()
const router = useRouter()
const loading = ref(false)
const questionData = ref(null)
const showLeft = ref(true)
const qCount = ref(0)
const currentIndex = ref(null)
const common=ref(null)
const firstTypeMap = {
  1: 'singleChoice',
  2: 'multipleChoice',
  3: 'judgement',
  4: 'fill',
  5: 'text',
  6: 'combination',
  7: 'indefiniteMultipleChoice'
}

const currentQuestion = computed(() => {
  if (currentIndex.value) {
    return questionData.value.content[currentIndex.value[0]].qs[currentIndex.value[1]];
  }
})


// 可为null和{}
const currentOptionsStatus = computed(() => {
  if (currentIndex.value != undefined) {
    let currentCard = questionData.value.content[currentIndex.value[0]].qs[currentIndex.value[1]];
    if (currentCard.answerStatus == 'done') {
      // 多选为数组
      let answer = currentCard.lockAnswer;
      // 多选为数组
      let rightAnswer = currentCard.rightAnswer;

      // 判断题选项0、1
      switch (currentCard.firstType) {
        case 1:
        case 3:
          if (answer == rightAnswer) {
            return {
              right: answer,
              wrong: ''
            }
          } else {
            return {
              right: rightAnswer,
              wrong: answer
            }
          }
          break;
          // 多选、不定项
        case 2:
        case 7:
          answer.sort((a, b) => {
            return a.charCodeAt(0) - b.charCodeAt(0)
          });
          answer = answer.toString();
          if (answer == rightAnswer.toString()) {
            return {
              right: rightAnswer,
              wrong: [],
              noSelected: []
            }
          } else {
            let arr1 = answer.split(',')
            let arr2 = [...rightAnswer]
            let right = []
            let wrong = []
            let noSelected = []
            for (let i = 0; i < arr1.length; i++) {
              let findIndex = arr2.findIndex((e) => {
                return e == arr1[i]
              })
              // 正确且选中
              if (findIndex > -1) {
                right.push(arr1[i])
                arr2.splice(findIndex, 1)
              } else {
                wrong.push(arr1[i])
              }
            }
            noSelected.push(...arr2)
            return {
              right,
              wrong,
              noSelected
            }
          }
          break;
        case 4:
          return {}
          break;
        default:
          break;
      }
    }
    return {}
  }
})
const data1 = {
  "message": null,
  "apiDown": false,
  "code": 1,
  "data": {
    "createdTime": "2025-04-29 11:17:57",
    "modifyTime": "2025-04-29 11:17:57",
    "id": "1917055724560203776",
    "categoryId": 108,
    "day": "2025-04-29",
    "userId": "1881630540189143040",
    "qCount": 10,
    "continuityDay": 1,
    "name": "一级建造师-建设工程法规及相关知识-每日一练-20250429",
    "joinCount": 1,
    "records": null,
    "content": [
      {
        "tyName": "单项选择题",
        "desc": "每日一练-单项选择题",
        "score": 6,
        "sort": 0,
        "qs": [
          {
            "id": "108_1873915860268089358",
            "sort": 0,
            "score": 1
          },
          {
            "id": "108_1905166784525238286",
            "sort": 1,
            "score": 1
          },
          {
            "id": "108_1914226477801406498",
            "sort": 2,
            "score": 1
          },
          {
            "id": "108_1905166781681500197",
            "sort": 3,
            "score": 1
          },
          {
            "id": "108_1905166775696228359",
            "sort": 4,
            "score": 1
          },
          {
            "id": "108_1873915544017567784",
            "sort": 5,
            "score": 1
          }
        ]
      },
      {
        "tyName": "多项选择题",
        "desc": "每日一练-多项选择题",
        "score": 4,
        "sort": 1,
        "qs": [
          {
            "id": "108_1873915981642858498",
            "sort": 0,
            "score": 1
          },
          {
            "id": "108_1914226497917288454",
            "sort": 1,
            "score": 1
          },
          {
            "id": "108_1914219562094559248",
            "sort": 2,
            "score": 1
          },
          {
            "id": "108_1914226489646120970",
            "sort": 3,
            "score": 1
          }
        ]
      }
    ]
  },
  "success": true
}
const data2 = {
  "message": null,
  "apiDown": false,
  "code": 1,
  "data": {
    "id": "108_1873915860268089358",
    "firstType": 1,
    "type": "单项选择题",
    "difficulty": "easy",
    "stem": [
      {
        "vl": "根据《建设工程抗震管理条例》，实行施工总承包的，隔震减震装置属于建设工程主体结构的施工，应当由（    ）。",
        "tp": "html"
      }
    ],
    "quOption": [
      {
        "content": [
          {
            "vl": "总承包单位自行完成",
            "tp": "html"
          }
        ],
        "option": "A"
      },
      {
        "content": [
          {
            "vl": "分包单位完成",
            "tp": "html"
          }
        ],
        "option": "B"
      },
      {
        "content": [
          {
            "vl": "总承包单位于分包单位共同完成",
            "tp": "html"
          }
        ],
        "option": "C"
      },
      {
        "content": [
          {
            "vl": "隔震减震装置的制造方完成",
            "tp": "html"
          }
        ],
        "option": "D"
      }
    ],
    "answerDesc": [
      {
        "vl": "P242<br/>《建设工程抗震管理条例》规定，实行施工总承包的，隔震减震装置属于建设工程主体结构的施工，应当由总承包单位自行完成。",
        "tp": "html"
      }
    ],
    "children": null,
    "record": {
      "as": "A",
      "rt": true,
      "t": 1745912425521
    },
    "rightAnswer": "A",
    "answerBase64": null,
    "sign": "e284b1bc34c0a03f56af981ca81a332a",
    "collect": false,
    "cid": null,
    "cn": null,
    "sourceId": "20240412173803-0641a94e-8d75-4c9c-a0ab-7c639b7b1db8",
    "doingNumber": 1,
    "errorNumber": 0
  },
  "success": true
}


function init() {
  PaperApis.todayPractice({
    params: {
      categoryId: route.query.categoryId
    }
  }).then(res => {
    if(!res.data.content.length){
      ElMessage({
        message: '没有题目了',
        type: 'warning',
      })
      router.go(-1)
      return;
    }
    let num = 0
    res.data.content=res.data.content.filter(e=>{
      return e.qs.length>0
    })
    // 每日一练有空的大题型，必须删除
    res.data.content.forEach(ele => {
      ele.qs.forEach(ele1 => {
        num++;
        ele1.num = num;
        ele1.answer = '';
      })
    })
    qCount.value = num;
    // 获取都一道题
    getOneQuestion(res.data.content[0].qs[0].id).then(res1 => {
      questionData.value = res.data;
      // let obj = {
      //   "id": "108_1873915860268089358",
      //   "firstType": 1,
      //   "type": "单项选择题",
      //   "difficulty": "easy",
      //   "stem": [
      //     {
      //       "vl": "根据《建设工程抗震管理条例》，实行施工总承包的，隔震减震装置属于建设工程主体结构的施工，应当由（    ）。",
      //       "tp": "html"
      //     }
      //   ],
      //   "quOption": [
      //     {
      //       "content": [
      //         {
      //           "vl": "总承包单位自行完成",
      //           "tp": "html"
      //         }
      //       ],
      //       "option": "A"
      //     },
      //     {
      //       "content": [
      //         {
      //           "vl": "分包单位完成",
      //           "tp": "html"
      //         }
      //       ],
      //       "option": "B"
      //     },
      //     {
      //       "content": [
      //         {
      //           "vl": "总承包单位于分包单位共同完成",
      //           "tp": "html"
      //         }
      //       ],
      //       "option": "C"
      //     },
      //     {
      //       "content": [
      //         {
      //           "vl": "隔震减震装置的制造方完成",
      //           "tp": "html"
      //         }
      //       ],
      //       "option": "D"
      //     }
      //   ],
      //   "answerDesc": [
      //     {
      //       "vl": "P242<br/>《建设工程抗震管理条例》规定，实行施工总承包的，隔震减震装置属于建设工程主体结构的施工，应当由总承包单位自行完成。",
      //       "tp": "html"
      //     }
      //   ],
      //   "children": null,
      //   "record": {
      //     "as": "A",
      //     "rt": true,
      //     "t": 1745912425521
      //   },
      //   "rightAnswer": "A",
      //   "answerBase64": null,
      //   "sign": "e284b1bc34c0a03f56af981ca81a332a",
      //   "collect": false,
      //   "cid": null,
      //   "cn": null,
      //   "sourceId": "20240412173803-0641a94e-8d75-4c9c-a0ab-7c639b7b1db8",
      //   "doingNumber": 1,
      //   "errorNumber": 0,
      //
      //
      //   "num": 1,
      //   "answerStatus": "notDone",
      //   "current": true,
      //   "note": '',
      //   "isTrue": false,
      // }

      res1.data.num=1
      res1.data.answerStatus="notDone"
      res1.data.current=true
      res1.data.note=''
      res1.data.isTrue=false

      initAnswer(res1.data, res1.data.record ? res1.data.record.as : null, res1.data.firstType)

      questionData.value.content[0].qs[0] = res1.data
      currentIndex.value = [0, 0];
      router.replace({
        query: {...route.query, name: questionData.value.name,id: questionData.value.id}
      })
    })
  })
}

function initAnswer(targetObj, right, firstType) {
  if (right) {
    if (firstType == 4) {
      let array = right.split(' ')
      for (let i = 0; i < array.length; i++) {
        targetObj['answer' + i] = array[i]
      }
      targetObj.answer = e.record.as
    } else {
      try {
        targetObj.answer = JSON.parse(right)
        targetObj.lockAnswer = JSON.parse(right)
      } catch (err) {
        targetObj.answer = right
        targetObj.lockAnswer = right
      }
    }
  } else {
    if (firstType == 4) {
      let array = right.split(' ')
      for (let i = 0; i < targetObj.quOption.length; i++) {
        targetObj['answer' + i] = null
      }
      targetObj.answer = null
    } else {
      targetObj.answer = [1, 3, 5].includes(firstType) ? '' : [];
      targetObj.lockAnswer = [1, 3, 5].includes(firstType) ? '' : [];
    }
  }
}

function saveAndExit() {

}

function getOneQuestion(id) {
  return PaperApis.doOne(null, {
    params: {
      id,
      industryCode: route.query.industryCode,
      examId: route.query.examId,
      categoryId: route.query.categoryId,
      view: true,
      ct: "everyday",
      oneDoSource: 'erveryDay'
    },
    headers: {
      "content-type": "application/x-www-form-urlencoded;"
    }
  });
}

// 如果没有请求过，则请求数据；如果请求过，则直接赋值
// 改变currentIndex
function preQuestion() {
  let tempArr=[]
  let current = currentQuestion.value.num
  if (current <= 1) {
    return
  }
  currentQuestion.value.current = false;
  let aa = 0
  a:for (let i of questionData.value.content) {
    let b = 0;
    for (let j of i.qs) {
      if (j.num == current - 1) {

        tempArr = [aa, b]
        j.current = true;
        break a;
      }
      b++
    }
    aa++
  }
  if (!questionData.value.content[tempArr[0]].qs[tempArr[1]].stem) {
    getOneQuestion(!questionData.value.content[tempArr[0]].qs[tempArr[1]].id).then(res => {
      let obj = {
        ...res.data, ...questionData.value.content[tempArr[0]].qs[tempArr[1]],
        current: true,
        isTrue: false,
        note: '',
        answerStatus: 'notDone'
      }
      initAnswer(obj, obj.record ? obj.record.as : null, obj.firstType)
      questionData.value.content[tempArr[0]].qs[tempArr[1]]=obj
    }).finally(()=>{
      currentIndex.value = tempArr
    })
  }else{
    currentIndex.value = tempArr
  }

}

function changeCurrent(i, j) {
  let tempArr=[i, j]
  const [index1, index2] = currentIndex.value
  questionData.value.content[index1].qs[index2].current = false
  questionData.value.content[i].qs[j].current = true


  if (!questionData.value.content[i].qs[j].stem) {
    getOneQuestion(questionData.value.content[i].qs[j].id).then(res => {
      let obj = {
        ...res.data, ...questionData.value.content[tempArr[0]].qs[tempArr[1]],
        current: true,
        isTrue: false,
        note: '',
        answerStatus: 'notDone'
      }
      initAnswer(obj, obj.record ? obj.record.as : null, obj.firstType)
      questionData.value.content[tempArr[0]].qs[tempArr[1]]=obj
    }).finally(()=>{
      currentIndex.value = tempArr
    })
  }else{
    currentIndex.value = tempArr
  }
}

function doNote(){
//   用el-drawer
  common.value.setDraw(true)
//   获取笔记详情
  NoteApis.getNoteList({
    params:{
      type:'everyDayPractice',
      relationId:route.query.id,
      questionId:currentQuestion.value.id,
      categoryId:route.query.categoryId,
    }
  }).then(res=>{
    if(res.data.length>0){
      common.value.noteAction='edit'
      common.value.setFormData(res.data[0])
    }else{
      common.value.noteAction='save'
    }
  })
}

function saveNote(formData){
  if(common.value.noteAction=='save'){
    NoteApis.publishNote({
      ...formData,
      type:'everyDayPractice',
      // 关联id就是章节id之类的
      relationId:route.query.id,
      // verify:'',
      questionId:currentQuestion.value.id,
      categoryId:route.query.categoryId,
    }).then(res=>{
      common.value.setDraw(false)
      ElMessage({
        message:'笔记保存成功',
        type:'success'
      })
    }).catch(_=>{
      ElMessage({
        message:'笔记保存失败',
        type:'error'
      })
    })
  }else{
    NoteApis.updateNote({
      ...formData,
    }).then(res=>{
      common.value.setDraw(false)
      ElMessage({
        message:'笔记更新成功',
        type:'success'
      })
    }).catch(_=>{
      ElMessage({
        message:'笔记更新失败',
        type:'error'
      })
    })
  }
}

// 直接与rightAnswer对比，不发送请求
async function submitThis() {

  const currentCard = questionData.value.content[currentIndex.value[0]].qs[currentIndex.value[1]];
  // 已经提交做了的不能重复提交
  if (currentCard.answerStatus == 'done') {
    return;
  }
  // 提交本题答案请求
  let answer = currentCard.answer;
  if (answer == null || answer == '' || answer.length == 0) {
    ElMessage('请选择答案')
    return;
  }
  if (currentCard.firstType == 4) {
    let arr = [];
    for (let i = 0; i < currentCard.length; i++) {
      arr.push(currentCard['answer' + i].trim())
    }
    currentCard.lockAnswer = arr.join(' ')
  } else {
    currentCard.lockAnswer = currentCard.answer
  }
  let as
  switch (currentCard.firstType) {
    case 1:
    case 2:
    case 3:
    case 5:
    case 7:
      as = answer;
      break;
    case 4:
      let arr = [];
      for (let i = 0; i < currentCard.quOption.length; i++) {
        arr.push(currentCard['answer' + i].trim())
      }
      as = arr.join(' ')
      break;
    default:

  }


  currentCard.answerStatus = 'done';
  // 正确
  if (as instanceof Array) {
    as.sort((a, b) => {
      return a.charCodeAt(0) - b.charCodeAt(0)
    })
    if (as.join('') == currentCard.rightAnswer.join(''))
      currentCard.isTrue = true;
    else currentCard.isTrue = false;
  } else {
    if (as == currentCard.rightAnswer) currentCard.isTrue = true;
    else
      currentCard.isTrue = false;
  }
  questionData.value.lastId = currentQuestion.value.id
}

function nextQuestion() {
  let tempArr=[]
  let current = currentQuestion.value.num
  if (current >= qCount.value) {
    return
  }
  currentQuestion.value.current = false;
  let aa = 0
  a:for (let i of questionData.value.content) {
    let b = 0;
    for (let j of i.qs) {
      if (j.num == current + 1) {
        tempArr=[aa,b]
        j.current = true;
        break a;
      }
      b++
    }
    aa++
  }
  if (!questionData.value.content[tempArr[0]].qs[tempArr[1]].stem) {
    getOneQuestion(questionData.value.content[tempArr[0]].qs[tempArr[1]].id).then(res => {
      let obj = {
        ...res.data, ...questionData.value.content[tempArr[0]].qs[tempArr[1]],
        current: true,
        isTrue: false,
        note: '',
        answerStatus: 'notDone'
      }
      initAnswer(obj, obj.record ? obj.record.as : null, obj.firstType)
      questionData.value.content[tempArr[0]].qs[tempArr[1]]=obj

    }).finally(()=>{
      currentIndex.value = tempArr
    })
  }else{
    currentIndex.value = tempArr
  }
}

function toggleNote() {
  if (!currentQuestion.value.collect) {
    QuestionApis.collectQuestion({
      industryCode:route.query.industryCode,
      examId:route.query.examId,
      categoryId:route.query.categoryId,
      // industryName: userStore.selectCategory.industryName,
      // examName: userStore.selectCategory.examName,
      // categoryName: userStore.selectCategory.categoryName,
      columnId: route.query.columnId,
      qid: currentQuestion.value.id,
      true: true,
      recordsType: 'paperRecordChapterPractice',
      data: {
        qt: currentQuestion.value.firstType,
        // qt: firstTypeMap1[currentQuestion.value.firstType],
        tr: '',
        // 章节id为试卷id吗
        cid: route.query.id,
        ct: 'paperRecordChapterPractice',
        cn: route.query.name,
        as: currentQuestion.value.answer,
        sn: currentQuestion.value.sign,
        t: new Date().getTime(),
        st: currentQuestion.value.stem

      }
    }).then(res => {
      if (res.data == true) {
        currentQuestion.value.collect = true
        currentQuestion.value.notedTime = new Date().getTime()
      }
      // QuestionApis.paperRecordsCollect(localStore.userSelectedIdsMap)
    })
  } else {
    QuestionApis.delCollect({
      industryCode:route.query.industryCode,
      examId:route.query.examId,
      categoryId:route.query.categoryId,
      // industryName: userStore.selectCategory.industryName,
      // examName: userStore.selectCategory.examName,
      // categoryName: userStore.selectCategory.categoryName,
      columnId: route.query.columnId,
      qid: currentQuestion.value.id,
    }).then(res => {
      if (res.success == true) {
        currentQuestion.value.collect = false
        currentQuestion.value.notedTime = 0
      }
    })
  }
}

function toggle() {
  showLeft.value = !showLeft.value
}

init()

</script>

<template>
  <div>
    <CommonQuestion
        ref="common"
        :change-checkbox="()=>{}"
        :change-current="changeCurrent"
        :change-radio="()=>{}"
        :current-options-status="currentOptionsStatus"
        :current-question="currentQuestion"
        :do-note="doNote"
        :save-and-exit="saveAndExit"
        :q-count="qCount"
        :pre-question="preQuestion"
        :submit-this="submitThis"
        :next-question="nextQuestion"
        :toggle-note="toggleNote"
        :toggle="toggle"
        :loading="loading"
        :save-note="saveNote"
        :show-left="showLeft"
        :question-data="questionData"
        paper-mode="practice"

    />
  </div>
</template>

<style scoped>

</style>